package com.sduept.tool;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import javax.xml.bind.JAXBContext;
//import javax.xml.bind.Marshaller;
//import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Set;

public class PrintTool {
    private static Logger logger = LoggerFactory.getLogger(PrintTool.class);

    public static String bytes2hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        String tmp = null;
        for (byte b : bytes) {
            // 将每个字节与0xFF进行与运算，然后转化为10进制，然后借助于Integer再转化为16进制
            tmp = Integer.toHexString(0xFF & b);
            if (tmp.length() == 1) {
                tmp = "0" + tmp;
            }
            sb.append(tmp + " ");
        }
        return "共:"+bytes.length+"字节:" + sb.toString();
    }
    
    public static String bytes2hexLines(byte[] bytes, int offset, int length) {
        StringBuilder sb = new StringBuilder();
        String tmp = null;
        for (int i = 0; i < length; i++) {
            // 将每个字节与0xFF进行与运算，然后转化为10进制，然后借助于Integer再转化为16进制
            tmp = Integer.toHexString(0xFF & bytes[offset + i]);
            if (tmp.length() == 1) {
                tmp = "0" + tmp;
            }
            if(i>0&&i%10==0) {
            	sb.append(tmp + "\n");
            }
            sb.append(tmp + " ");
        }
        return sb.toString();
    }
    public static String bytes2hex(byte[] bytes, int offset, int length) {
        StringBuilder sb = new StringBuilder();
        String tmp = null;
        for (int i = 0; i < length; i++) {
            // 将每个字节与0xFF进行与运算，然后转化为10进制，然后借助于Integer再转化为16进制
            tmp = Integer.toHexString(0xFF & bytes[offset + i]);
            if (tmp.length() == 1) {
                tmp = "0" + tmp;
            }
            sb.append(tmp + " ");
        }
        return "共:"+length+"字节:" + sb.toString();
    }
    public static ByteBuffer string2byte(String hexString){
        String[] strs = hexString.split(" ");
        byte[] hexByte = new byte[hexString.length()];
        for(int i = 0 ;i<strs.length;i++){
            int in = Integer.parseInt(strs[i],16) & 0xFF;
            hexByte[i] = (byte)in;
        }
        ByteBuffer buffer = ByteBuffer.wrap(hexByte);
        return buffer;
    }
//    public static String objectToXml(Object object){
//        String xml = "";
//        try {
//            JAXBContext context=JAXBContext.newInstance(object.getClass());
//            Marshaller marshaller=context.createMarshaller();
//            //是否格式化输出
//            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//            //编码格式
//            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
//            //是否省略xml的头信息
//            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
//            StringWriter sw=new StringWriter();
//            marshaller.marshal(object, sw);
//            xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+sw.toString();
//        } catch (Exception e) {
//            logger.error("objectToXml异常", e);
//        }
//        return xml;
//    }

    /**
     * 根据文件路径找到对应的xml文件
     * 转换成实体类
     * @param path
     * @return
     */
//    public static Object xmlToObject(String path,Class class1,Object object){
//        FileInputStream fileIn = null;
//        try {
//            File file = new File(path);
//            boolean fileIsUtf8 = CharsetUtil.isUtf8(file); //判断xml文件编码格式
//            fileIn = new FileInputStream(file);
//            ByteArrayOutputStream out=new ByteArrayOutputStream();
//            byte[] xml = new byte[fileIn.available()];
//            while(fileIn.available() > 0){
//                fileIn.read(xml);
//            }
//            JAXBContext context=JAXBContext.newInstance(class1);
//            Unmarshaller jaxUnmarshaller=context.createUnmarshaller();
//
//            StringReader sr = null;
//            if(fileIsUtf8) { //UTF-8
//                sr=new StringReader(new String(xml,Charset.forName("utf-8")));
//            } else { //GBK
//                String value = new String(xml,Charset.forName("GBK"));
//                byte[] utfStr = value.getBytes(Charset.forName("utf-8"));
//                sr=new StringReader(new String(utfStr,Charset.forName("utf-8")));
//            }
//            object =jaxUnmarshaller.unmarshal(sr);
//            sr.close();
//            //sub = (SubModel) object;
//        } catch (Exception e) {
//            logger.error("xmlToObject", e);
//        }finally{
//            try {
//                if(fileIn != null){
//                    fileIn.close();
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        return object;
//    }
    /*
    数组转换 成整数
     */
    public static int bytesToInt(byte[] b) {
        int temp = 0;
        int accum = 0;
        for(int i = 0 ;i<b.length;i++){
            int t = i*8;
            accum = accum | (b[i]&0xff) << t;
        }
        return accum;
    }
    public static float byteToFloat(byte[] b){
        int accum = 0;
        accum = accum|(b[0] & 0xff) << 0;
        accum = accum|(b[1] & 0xff) << 8;
        accum = accum|(b[2] & 0xff) << 16;
        accum = accum|(b[3] & 0xff) << 24;
        return Float.intBitsToFloat(accum);
    }
    public static double byteToDouble(byte[] b){
        long accum = 0;
        accum = accum|(b[0] & 0xff) << 0;
        accum = accum|(b[1] & 0xff) << 8;
        accum = accum|(b[2] & 0xff) << 16;
        accum = accum|(b[3] & 0xff) << 24;
        accum = accum|(b[4] & 0xff) << 32;
        accum = accum|(b[5] & 0xff) << 40;
        accum = accum|(b[6] & 0xff) << 48;
        accum = accum|(b[7] & 0xff) << 56;
        return Double.longBitsToDouble(accum);
    }

    /**
     * 判断字符的编码格式
     */
    public static  String getEncoding(String str){
        String encode = "UTF-8";
        try {
//            if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是UTF-8
//                String s2 = encode;
//                return s2;
//            }
        } catch (Exception exception2) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是GBK
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return "";
    }
    /*
     * 中文转unicode编码
     */
    public static String unicode(String gbString) {
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int i = 0; i < utfBytes.length; i++) {
            String hexB = Integer.toHexString(utfBytes[i]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes =  unicodeBytes +"\\u" + hexB;
        }
        return unicodeBytes;
    }

    /**
     * 中文转Unicode（只转中文）
     * @param gbString
     * @return
     */
    public static String unicodeToUn4Cn(String gbString) {
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int i = 0; i < utfBytes.length; i++) {
            char utfChar = utfBytes[i];
            if(isChineseChar(utfChar)) {
                String hexB = Integer.toHexString(utfChar);
                if (hexB.length() <= 2) {
                    hexB = "00" + hexB;
                }
                unicodeBytes =  unicodeBytes +"\\u" + hexB;
            }else {
                unicodeBytes = unicodeBytes + utfChar;
            }
        }
        return unicodeBytes;
    }

    /**
     * 判断是否是中文
     * @param c
     * @return
     */
    public static boolean isChineseChar(char c) {
        return String.valueOf(c).matches("[\u4e00-\u9fa5]");
    }

    public static void printAllThreadNames (){
        ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
        int noThreads = currentGroup.activeCount();
        Thread[] lstThreads = new Thread[noThreads];
        currentGroup.enumerate(lstThreads);
        logger.info("当前线程数为{}个", noThreads);
        String testMode = "true";
        if(testMode != null) {
            for (int i = 0; i < noThreads; i++) {
                logger.info("线程号：" + i + " = " + lstThreads[i].getName());
            }
        }
    }
}
